package com.easy.back.controller;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easy.back.pojo.ErrorLog;
import com.easy.back.pojo.HouseInformation;
import com.easy.back.pojo.PUser;
import com.easy.back.pojo.R;
import com.easy.back.pojo.dto.HouseInformationDto;
import com.easy.back.service.IHouseInformationService;
import com.easy.back.service.IPUserService;
import com.easy.back.utils.BaseContext;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.easy.back.utils.RedisConstants.HOUSE_CONTRACTION_KEY;

/**
 * 房子控制器
 *
 * @author RuoYu
 * @date 2022/12/31
 */
@RestController
@RequestMapping("/house")
public class HouseController {

    @Autowired
    private IHouseInformationService houseInformationService;


    @Autowired
    private IPUserService pusUserService;

    @Resource(name = "redisTemplateHouse")
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param title
     * @return
     */
    @GetMapping("/page")
    public R<Page<HouseInformationDto>> list(int page, int pageSize, String title) {

        //分页构造器
        Page<HouseInformation> pageInfo = new Page<>(page, pageSize);
        Page<HouseInformationDto> houseInformationDtoPage = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<HouseInformation> lqw = new LambdaQueryWrapper<>();

        lqw.like(Strings.isNotEmpty(title), HouseInformation::getTitle, title);
        //添加排序条件，根据sort进行排序
        lqw.orderByDesc(HouseInformation::getStatus);
        lqw.orderByDesc(HouseInformation::getPermissions);
        //执行分页查询
        houseInformationService.page(pageInfo, lqw);

        BeanUtils.copyProperties(pageInfo, houseInformationDtoPage, "records");
        //3、获取数据
        List<HouseInformation> records = pageInfo.getRecords();
        List<HouseInformationDto> houseInformationDtoList = records.stream().map((item) -> {
            HouseInformationDto houseInformationDto = new HouseInformationDto();
            //将数据赋值给dishDto
            BeanUtils.copyProperties(item, houseInformationDto);

            LambdaQueryWrapper<PUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PUser::getId, houseInformationDto.getHouseOwner());
            // 获取平台用户信息
            PUser pUser = pusUserService.getOne(wrapper);
            houseInformationDto.setUserName(pUser.getUserName());
            return houseInformationDto;
        }).collect(Collectors.toList());
        houseInformationDtoPage.setRecords(houseInformationDtoList);

        return R.success(houseInformationDtoPage);
    }


    /**
     * 根据id删除房屋信息
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/d")
    public R<String> delete(String ids) {
        BaseContext.set(ids);
        String[] id = ids.split(",");
        for (String s : id) {
            houseInformationService.removeById(s);

            HashMap<String, Object> houseMap = new HashMap<>();
            houseMap.put("deletedFlag", "-1");
            // 更新房屋缩略信息缓存
            redisTemplate.opsForHash().putAll(HOUSE_CONTRACTION_KEY + s, houseMap);
        }
        return R.success("删除成功");
    }

    /**
     * 根据id更改房屋状态
     *
     * @param id
     * @return
     */
    @PostMapping("/status/{id}/{status}")
    public R<String> update(@PathVariable String id, @PathVariable int status) {
        BaseContext.set("id:" + id + "," + "status:" + status);
        String permissions = "0";
        if (status == 1) {
            permissions = "1";
        }
        LambdaUpdateWrapper<HouseInformation> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(HouseInformation::getStatus, status);
        wrapper.set(HouseInformation::getPermissions, permissions);
        wrapper.eq(HouseInformation::getId, id);
        houseInformationService.update(wrapper);

        HashMap<String, Object> houseMap = new HashMap<>();
        houseMap.put("status", permissions);
        // 6.更新房屋缩略信息缓存
        redisTemplate.opsForHash().putAll(HOUSE_CONTRACTION_KEY + id, houseMap);

        return R.success("修改成功");
    }

    @PutMapping("/u")
    public R<String> update(@RequestBody HouseInformationDto houseInformationDto) {

        HouseInformation houseInformation = new HouseInformation();
        BeanUtils.copyProperties(houseInformationDto, houseInformation);

        BaseContext.set(houseInformation);

        houseInformation.setPermissions("0");
        houseInformationService.updateById(houseInformation);
        // 更新房屋缩略信息缓存
        HashMap<String, Object> houseMap = getHouseMap(houseInformationDto);
        redisTemplate.opsForHash().putAll(HOUSE_CONTRACTION_KEY + houseInformationDto.getId(), houseMap);
        return R.success("房屋信息修改成功");
    }

    /**
     * 回显
     */
    @GetMapping("/{id}")
    public R<HouseInformationDto> get(@PathVariable Long id) {
        HouseInformationDto houseInformationDto = houseInformationService.getById(id);
        return R.success(houseInformationDto);
    }

    private HashMap<String, Object> getHouseMap(HouseInformation houseDto) {
        HashMap<String, Object> houseMap = new HashMap<>();
        houseMap.put("title", houseDto.getTitle());
        houseMap.put("img", houseDto.getImg());
        houseMap.put("price", houseDto.getPrice());
        houseMap.put("areaSize", houseDto.getAreaSize());
        houseMap.put("status", houseDto.getStatus());
        houseMap.put("deletedFlag", houseDto.getDeletedFlag());
        return houseMap;
    }
}
